package cn.xm.basic.interceptor;

import cn.xm.user.domain.Logininfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.util.concurrent.TimeUnit;

@Component
public class MyInterceptor implements HandlerInterceptor {
    @Autowired
    private RedisTemplate redisTemplate;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 从请求头获取前置拦截器加的token
        String token = request.getHeader("U-TOKEN");
        Logininfo logininfo = null;
        // 如果token存在
        if (!StringUtils.isEmpty(token)) {
            // 从redis里查是否有该用户信息
            logininfo = (Logininfo)redisTemplate.opsForValue().get(token);
        }
        // 有则放行
        if (logininfo != null) {
            // 刷新redis中用户信息保存时间
            redisTemplate.opsForValue().set(token,logininfo,30, TimeUnit.MINUTES);
            return true;
        }
        // 设置字符集
        response.setCharacterEncoding("UTF-8");
        response.setContentType("text/json; charset=utf-8");
        // 没有表示没登录或过期
        PrintWriter writer = response.getWriter();
        writer.write("{\"success\":false,\"message\":\"nologin\",\"resultObj\":null}");
        // 刷新并关流
        writer.flush();
        writer.close();
        return false;
    }

}
